package com.ts.animal.controller;

import com.alibaba.fastjson.JSON;
import com.ts.animal.constant.AnimalConstant;
import com.ts.animal.domain.BaseStationDO;
import com.ts.animal.domain.BaseStationHeartBeatOriginalDataDO;
import com.ts.animal.domain.BaseStationRevOriginalDataDO;
import com.ts.animal.domain.HeartbeatRecordDO;
import com.ts.animal.service.BaseStationService;
import com.ts.animal.service.HeartbeatRecordService;
import com.ts.common.redis.RedisUtil;
import com.ts.common.utils.Result;
import com.ts.common.utils.SpringUtils;
import com.ts.common.utils.StringUtils;
import com.ts.common.utils.UtilString;
import com.ts.system.domain.SystemParamsDO;
import com.ts.system.util.SystemUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author bobby
 * 基站对接 回调
 */
@Controller
@RequestMapping("/earcon")
public class BaseStationCallbackController {

    private static Logger log = LoggerFactory.getLogger(BaseStationCallbackController.class);

    @Autowired
    private BaseStationService baseStationService;
    @Autowired
    private HeartbeatRecordService heartbeatRecordService;


    @RequestMapping("/conf")
    /**
     * @Log("基站配置信息")
     * @no 采集基站设备序列号
     * @ver 固件版本号
     */
    @ResponseBody
    public Map<String, Object> conf(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String no = request.getParameter("no");
        String ver = request.getParameter("ver");
        log.info("基站配置信息，基站设备序列号[{}],版本号：{}", no, ver);
        Map<String, Object> data = new HashMap<String, Object>();
        if (SystemUtil.getSystemParams().get(AnimalConstant.key_name_base_station_send_data_interval_duration) != null) {
            data.put("rpm", SystemUtil.getSystemParams().get(AnimalConstant.key_name_base_station_send_data_interval_duration).getParamValue());
        }
        if (SystemUtil.getSystemParams().get(AnimalConstant.key_name_base_station_data_size) != null) {
            data.put("size", SystemUtil.getSystemParams().get(AnimalConstant.key_name_base_station_data_size).getParamValue());
        }
        if (SystemUtil.getSystemParams().get(AnimalConstant.key_name_base_station_callback_url) != null) {

            data.put("dataurl", SystemUtil.getSystemParams().get(AnimalConstant.key_name_base_station_callback_url).getParamValue());
        }
        if (SystemUtil.getSystemParams().get(AnimalConstant.key_name_base_station_ota_url) != null) {
            data.put("otaurl", SystemUtil.getSystemParams().get(AnimalConstant.key_name_base_station_ota_url).getParamValue());
        }
        if (SystemUtil.getSystemParams().get(AnimalConstant.key_name_base_station_wifi_name) != null) {
            data.put("wifiname", SystemUtil.getSystemParams().get(AnimalConstant.key_name_base_station_wifi_name).getParamValue());
        }
        if (SystemUtil.getSystemParams().get(AnimalConstant.key_name_base_station_wifi_password) != null) {
            data.put("wifipwd", SystemUtil.getSystemParams().get(AnimalConstant.key_name_base_station_wifi_password).getParamValue());
        }
        if (SystemUtil.getSystemParams().get(AnimalConstant.key_name_base_station_heartbeat) != null) {
            data.put("heartbeat", SystemUtil.getSystemParams().get(AnimalConstant.key_name_base_station_heartbeat).getParamValue());
        }
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("co", 200);
        result.put("da", data);
        return result;
    }


    @RequestMapping("/heartbeat")
    @ResponseBody
    /**
     *  @Log("接收基站心跳")
     *  @no 采集基站设备序列号
     */
    public Map<String, Object> heartbeat(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取请求参数json POST
        String no = request.getParameter("no");
        String dataString = UtilString.getString(request.getInputStream());
        log.info("接收基站心跳,基站设备信息dataString:[{}]", dataString);
        log.info("接收基站心跳,基站设备信息号[{}]", no);
        try {
            //转换数据
            BaseStationHeartBeatOriginalDataDO baseStationRevOriginalDataDO = JSON.parseObject(dataString, BaseStationHeartBeatOriginalDataDO.class);
            log.info("接收基站心跳,baseStationRevOriginalDataDO:[{}]", JSON.toJSONString(baseStationRevOriginalDataDO));
            if(baseStationRevOriginalDataDO!=null){
                no =baseStationRevOriginalDataDO.getNo();
                BaseStationDO baseStationDO = new BaseStationDO();
                baseStationDO.setBaseStationNum(no);
                baseStationDO.setDaBattery(baseStationRevOriginalDataDO.getDaObject().getBattery());
                baseStationDO.setDaElec(baseStationRevOriginalDataDO.getDaObject().getElec());
                baseStationDO.setDaG24(baseStationRevOriginalDataDO.getDaObject().getG24());
                baseStationDO.setDaGps(baseStationRevOriginalDataDO.getDaObject().getGps());
                baseStationDO.setDaGsm(baseStationRevOriginalDataDO.getDaObject().getGsm());
                baseStationDO.setDaLan(baseStationRevOriginalDataDO.getDaObject().getLan());
                baseStationDO.setDaPower(baseStationRevOriginalDataDO.getDaObject().getPower());
                baseStationDO.setDaPowerVol(baseStationRevOriginalDataDO.getDaObject().getPowerVol());
                baseStationDO.setDaWlan(baseStationRevOriginalDataDO.getDaObject().getWlan());
                baseStationService.update(Result.ok(),baseStationDO);

                HeartbeatRecordDO heartbeatRecordDO = new HeartbeatRecordDO();
                BeanUtils.copyProperties(baseStationDO,heartbeatRecordDO);
                heartbeatRecordDO.setCreateTime(new Date());
                heartbeatRecordService.save(Result.ok(),heartbeatRecordDO);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        //TODO 更新状态
        if (StringUtils.isNotEmpty(no)) {
            SystemParamsDO paramsDO = SystemUtil.getSystemParams().get(AnimalConstant.key_name_base_station_receive_switch);
            if (paramsDO != null && paramsDO.getParamValue().equalsIgnoreCase(AnimalConstant.open)) {
                // RedisUtil.lpush(AnimalConstant.REDIS_BASE_STATION_HEAR_BEAT_DATA_KEY, dataString);
                Long timeOut = Long.valueOf(SystemUtil.getSystemParams().get(AnimalConstant.key_name_base_station_status_online_timeout).getParamValue());
                RedisUtil.set(AnimalConstant.REDIS_BASE_STATION_STATUS_KEY + no, AnimalConstant.base_station_status_online, timeOut, TimeUnit.MINUTES);
            } else {
                log.info("接收服务暂停！");
            }
        }
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("co", 200);
        return result;
    }


    @ResponseBody
    @RequestMapping("/receive")
    /**
     * @Log("接收基站同步的标签数据")
     * @no 采集基站设备序列号
     * @ver 数据
     */
    public Map<String, Object> receive(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //UtilSignature.checkSignature(request);
        // 获取请求参数 GET
        String no = request.getParameter("no");
        //获取请求参数json POST
        String dataString = UtilString.getString(request.getInputStream());
        log.info("接收基站同步的标签数据，基站设备序列号[{}],接收到数据：{}", no, dataString);
        if (StringUtils.isNotEmpty(dataString)) {
            SystemParamsDO paramsDO = SystemUtil.getSystemParams().get(AnimalConstant.key_name_base_station_receive_switch);
            if (paramsDO != null && paramsDO.getParamValue().equalsIgnoreCase(AnimalConstant.open)) {
                RedisUtil.lpush(AnimalConstant.REDIS_BASE_STATION_DATA_KEY, dataString.trim());
            } else {
                log.info("接收服务暂停！");
            }
        }
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("co", 200);
        return result;
    }

}
